package com.tanhua.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.sso.pojo.Comment;
import com.tanhua.sso.pojo.Movement;
import com.tanhua.sso.pojo.MovementTimeLine;
import com.tanhua.sso.utils.CommentType;
import com.tanhua.util.IdWorker;
import com.tanhua.util.TimeLineService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class MovementServiceImpi implements MovementsService{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    @Override
    public void publish(Movement movement) {
        movement.setPid(idWorker.getNextId("movement"));
        //发送动态
        mongoTemplate.save(movement);
        //获取发布信息id
        ObjectId id = movement.getId();
        //获取当前用户id
        Long userId = movement.getUserId();

        timeLineService.saveTimeLine(userId,id);
    }

    /*查看我的动态*/
    @Override
    public List<Movement> myMovement(Integer page, Integer pagesize, Long userid) {
        //查看好友时间表
        Criteria criteria = Criteria.where("userId").is(userid).and("state").is(1);
        //分页查询
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    /*查看好友的动态*/
    @Override
    public List<Movement> friendMovement(Integer page,Integer pagesize,Long userId) {
        //获取时间线表中,对我开放的动态
        Criteria criteria = Criteria.where("friendId").is(userId);
        Query created = Query.query(criteria).with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);
        //获取共享的时间线表
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(created, MovementTimeLine.class);
        //收集id
        List<ObjectId> collectId = movementTimeLines.stream().map(movementTimeLine -> movementTimeLine.getMovementId()).collect(Collectors.toList());
        //通过id查找动态,批量查询
        List<Movement> movementList = mongoTemplate.find(Query.query(Criteria.where("id").in(collectId).and("state").is(1)), Movement.class);
        return movementList;
    }

    /*随机查询*/
    @Override
    public List<Movement> randomMovement(Integer pagesize) {
        Criteria criteria = Criteria.where("state").is(1);
        //分页查询条件
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(pagesize),Aggregation.match(criteria));

        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation,Movement.class);
        //返回movement集合
        return movements.getMappedResults();
    }

    /*pid查询*/
    @Override
    public List<Movement> findBypids(List<Long> collectPid) {
        Criteria pid = Criteria.where("pid").in(collectPid);
        List<Movement> movementList = mongoTemplate.find(Query.query(pid), Movement.class);
        return movementList;
    }

    /*个人动态*/
    @Override
    public Movement getMovementByid(String movementId) {
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        if (movement.getState()!=1){
            throw new CustomException("未审核或已驳回");
        }
        return movement;
    }

    /*判断是否点赞*/
    @Override
    public boolean islike(ObjectId id, Long userId) {
        Criteria criteria = Criteria.where("publishId").is(id).and("userId").is(userId).and("commentType").is(CommentType.LIKE.getType());
        Comment one = mongoTemplate.findOne(Query.query(criteria), Comment.class);
        if (ObjectUtil.isNotEmpty(one)){
            return true;
        }else {
            return false;
        }
    }

    /*取消点赞*/
    @Override
    public Integer disLike(ObjectId id, Long userId) {
        Criteria criteria = Criteria.where("publishId").is(id).and("userId").is(userId).and("commentType").is(CommentType.LIKE.getType());
        //找出已点赞的记录,并删除
        Comment one = mongoTemplate.findOne(Query.query(criteria), Comment.class);
        mongoTemplate.remove(one);
        //修改当前动态的点赞数
        Query query = Query.query(Criteria.where("id").is(id));
        Update update=new Update();
        update.inc("likeCount",-1);
        //设置更新参数
        FindAndModifyOptions findAndModifyOptions=new FindAndModifyOptions();
        //更新并返回最新值
        findAndModifyOptions.returnNew(true);
        Movement andModify = mongoTemplate.findAndModify(query, update, findAndModifyOptions, Movement.class);
        Integer likeCount = andModify.getLikeCount();
        return likeCount;
    }

    //判断是否喜欢
    @Override
    public boolean isLove(ObjectId id, Long userId) {
        //判断是否已经喜欢的条件
        Criteria criteria = Criteria.where("publishId").is(id).and("userId").is(userId).and("commentType").is(CommentType.LOVE.getType());
        Comment comment = mongoTemplate.findOne(Query.query(criteria), Comment.class);
        if (ObjectUtil.isNotEmpty(comment)){
            return true;
        }else {
            return false;
        }
    }

    //取消喜欢
    @Override
    public Integer unLove(ObjectId id, Long userId) {
        Criteria criteria = Criteria.where("publishId").is(id).and("userId").is(userId).and("commentType").is(CommentType.LOVE.getType());
        //找出已喜欢的记录,并删除
        Comment one = mongoTemplate.findOne(Query.query(criteria), Comment.class);
        mongoTemplate.remove(one);
        //修改当前动态的喜欢数
        Query query = Query.query(Criteria.where("id").is(id));
        Update update=new Update();
        update.inc("loveCount",-1);
        //设置更新参数
        FindAndModifyOptions findAndModifyOptions=new FindAndModifyOptions();
        //更新并返回最新值
        findAndModifyOptions.returnNew(true);
        Movement andModify = mongoTemplate.findAndModify(query, update, findAndModifyOptions, Movement.class);
        Integer loveCount = andModify.getLoveCount();
        return loveCount;
    }

    //分页条件动态
    @Override
    public ResultVo<Movement> page(Integer page, Integer pagesize, Long uid, String state) {
        Query query=new Query();
        //判断用户是否存在
        if (ObjectUtil.isNotEmpty(uid)){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        //状态
        if (StrUtil.isNotEmpty(state)&&!"''".equals(state)){
            query.addCriteria(Criteria.where("state").is(Convert.toInt(state)));
        }

        //总条数
        Long count = mongoTemplate.count(query, Movement.class);

        query.with(Sort.by(Sort.Order.desc("created"))).skip((page-1)*pagesize).limit(pagesize);
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        Integer pages=(count.intValue()/pagesize)+1;
        return new ResultVo<Movement>(Convert.toInt(count),pagesize,pages,page,movementList);
    }

    //审核动态
    @Override
    public void updatePass(List<String> ids, Integer state) {
        if (ObjectUtil.isNotEmpty(ids)){
            for (String id : ids) {
                Criteria criteria = Criteria.where("id").is(new ObjectId(id));
                Update update=new Update();
                update.set("state",state);
                //修改状态
                mongoTemplate.updateFirst(Query.query(criteria),update,Movement.class);
            }
        }
    }
}
